package com.zcs.app.lucky.ui

import android.content.Intent
import android.text.TextUtils
import android.view.View
import cn.sxw.android.base.kt.BaseViewModel
import com.safframework.delegate.extras.extraDelegate
import com.zcs.app.lucky.base.BaseLuckyActivity
import com.zcs.app.lucky.data.LuckyDataCache
import com.zcs.app.lucky.data.PrizeDataCache
import com.zcs.app.lucky.databinding.ActivityLuckyResumeBinding

class LuckyResumeActivity : BaseLuckyActivity<ActivityLuckyResumeBinding, BaseViewModel>() {
    override fun needViewModel(): Boolean = false
    private val mId by extraDelegate(KEY_ID, "")

    // 懒加载机制
    override fun isLazyInit() = true
    private val mLucky by lazy {
        LuckyDataCache.findByIdOrNewInstance(mId)
    }

    // 程序已就绪
    override fun onReady() {
        binding.toolbar.tvToolbarTitle.text = "继续抽奖"
        binding.loadingLayout.visibility = View.VISIBLE
    }

    override fun onInit() {
        // 初始UI
        initView()
        // 初始化数据
        initData()
        // 初始化观察者
        initObserve()
    }

    override fun initObserve() {
    }

    override fun initData() {
        adapterHelper.prizeList.clear()
        adapterHelper.prizeList.addAll(PrizeDataCache.loadAllPrizes())
        mLucky.prizeList = adapterHelper.prizeList
        adapterHelper.initPrizeAdapter(binding.rvPrize, horizontal = true) {
            onCreatePrize(it.id)
        }
        hideLoading()
        // 展示抽奖人员
        adapterHelper.userList.clear()
        adapterHelper.userList.addAll(mLucky.group!!.list)
        adapterHelper.initUserAdapter(binding.rvUsers, spanCount = 4) {

        }
        // 信息
        binding.tvName.text = mLucky.name
        binding.tvDesc.text = mLucky.desc
        binding.tvGroupName.text = mLucky.group!!.niceName()
    }

    override fun initView() {
    }

    override fun hideLoading() {
        super.hideLoading()
        binding.loadingLayout.visibility = View.GONE
    }

    override fun addOnClickListener() {
        binding.toolbar.ivToolbarBack.setOnClickListener { onBackPressed() }
        binding.btnStart.setOnClickListener {
            resumeLucky()
        }
    }

    // 保存并开始
    private fun resumeLucky() {
        killMyself()
        val intent = Intent(this, LuckingActivity::class.java)
        intent.putExtra(KEY_ID, mLucky.id)
        launchActivity(intent)
    }

    private fun onCreatePrize(id: String = "") {
        goAdd = true
        if (TextUtils.isEmpty(id)) {
            launchActivity(AddPrizeActivity::class.java)
        } else {
            val intent = Intent(this, AddPrizeActivity::class.java)
            intent.putExtra(AddPrizeActivity.KEY_PRIZE_ID, id)
            launchActivity(intent)
        }
    }
}